package com.step.ems.common

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.step.ems.MainActivity
import com.step.ems.MainApplication
import com.step.ems.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import retrofit2.HttpException

fun ViewModel.launch(
    delayTime: Long = 0,
    onStart: () -> Unit = {},
    onError: (e: Throwable) -> Unit = { _: Throwable -> },
    onComplete: () -> Unit = {},
    state: MutableStateFlow<UiState>? = null,
    block: suspend CoroutineScope.() -> Unit,
) {
    viewModelScope.launch {
        try {
            onStart()
            if (delayTime > 0) delay(delayTime)
            block.invoke(this)
        } catch (e: Exception) {
            e.printStackTrace()
            onError(e)
            state?.value = UiState.Error(e.message)
            if (e is HttpException && e.code() == 401) {
                EventBus.emit(LoginEvent())
            } else if (e !is kotlinx.coroutines.CancellationException) {
                val errorHead = MainApplication.instance.getString(R.string.error)
                MainActivity.alertDialogEvent = e.message ?: errorHead
            }
        } finally {
            onComplete()
        }
    }
}